package mission2;

/**
 * @author jinxin
 * @date 2019-08-10
 *
 * 给出两个 非空 的链表用来表示两个非负的整数。其中，它们各自的位数是按照 逆序 的方式存储的，并且它们的每个节点只能存储 一位 数字。
 * 如果，我们将这两个数相加起来，则会返回一个新的链表来表示它们的和。
 * 您可以假设除了数字 0 之外，这两个数都不会以 0 开头。
 */
public class AddTwoNumbers {

    public static void main(String[] args) {
        ListNode a = new ListNode(0);
        ListNode b = a;
        b.next = new ListNode(9);

        ListNode c = new ListNode(0);
        ListNode d = c;
        d.next = new ListNode(1);
        d = d.next;
        d.next = new ListNode(9);
        d = d.next;
        d.next = new ListNode(9);
        d = d.next;
        d.next = new ListNode(9);
        d = d.next;
        d.next = new ListNode(9);
        d = d.next;
        d.next = new ListNode(9);
        d = d.next;
        d.next = new ListNode(9);
        d = d.next;
        d.next = new ListNode(9);
        d = d.next;
        d.next = new ListNode(9);
        d = d.next;
        d.next = new ListNode(9);

        System.out.println(addTwoNumbers(a.next, c.next));
    }

    public static class ListNode {

        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }


    //废案,精度缺失
    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode dummyHead = new ListNode(0);
        ListNode curr = dummyHead;
        int i = 0;
        int j = 0;
        int num1 = 0;
        int num2 = 0;

        System.out.println(l1.val);

        while (null != l1) {
            num1 += l1.val * (int) Math.pow(10, i);
            i++;
            l1 = l1.next;
        }


        while (null != l2) {
            num2 += l2.val * (int) Math.pow(10, j);
            j++;
            l2 = l2.next;
        }

        int addNum = num1 + num2;


        if (addNum == 0) {
            return dummyHead;
        }
        while (addNum > 0) {
            curr.next = new ListNode(addNum % 10);
            curr = curr.next;
            addNum = addNum / 10;
        }

        return dummyHead.next;
    }


    //大数相加
    public static ListNode addTwoNumbersTry(ListNode l1, ListNode l2) {
        ListNode dummyHead = new ListNode(0);
        ListNode p = l1, q = l2, curr = dummyHead;
        int carry = 0;
        while (p != null || q != null) {
            int x = (p != null) ? p.val : 0;
            int y = (q != null) ? q.val : 0;
            int sum = carry + x + y;
            carry = sum / 10;
            curr.next = new ListNode(sum % 10);
            curr = curr.next;
            if (p != null) {
                p = p.next;
            }
            if (q != null) {
                q = q.next;
            }
        }
        if (carry > 0) {
            curr.next = new ListNode(carry);
        }
        return dummyHead.next;
    }

}
